package com.banksoft.cps.service.impl;

import com.banksoft.cps.bean.AdminUser;
import com.banksoft.cps.bean.User;
import com.banksoft.cps.bean.common.ServiceException;
import com.banksoft.cps.constants.ErrorConstant;
import com.banksoft.cps.constants.WebConstant;
import com.banksoft.cps.dao.AdminUserDao;
import com.banksoft.cps.enums.UserType;
import com.banksoft.cps.service.AdminUserService;
import com.banksoft.cps.util.CacheUtil;
import com.banksoft.cps.util.StrGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by rongzhao.zhu on 2017/12/19.
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {
    @Autowired
    AdminUserDao adminUserDao;

    @Override
    public AdminUser login(String account, String password) throws ServiceException {
        if(StringUtils.isBlank(account)){
            throw new ServiceException(ErrorConstant.ec_param_null,ErrorConstant.em_user_account_null);
        }
        if(StringUtils.isBlank(password)){
            throw new ServiceException(ErrorConstant.ec_param_null,ErrorConstant.em_user_password_null);
        }
        AdminUser adminUser = adminUserDao.findByAccount(account);
        if(adminUser == null ){
            throw new ServiceException(ErrorConstant.ec_result_null,ErrorConstant.em_user_null);
        }
        if(!adminUser.getPassword().equals(password)){
            throw new ServiceException(ErrorConstant.ec_param_error,ErrorConstant.em_password_error);
        }
        String token =  token(adminUser);
        Map<String,String> cookieMap = new HashMap<>();
        cookieMap.put(WebConstant.cookieToken,token);
        cookieMap.put(WebConstant.cookieFake, StrGenerator.generateRandomStr(32));
        cookieMap.put(WebConstant.cookieName, StrGenerator.EncoderByMd5(adminUser.getName()));
        adminUser.setCookieMap(cookieMap);
        adminUser.setType(UserType.security.name());
        CacheUtil.cache(token,adminUser);

        return adminUser;
    }

    @Override
    public void logout(String token) {
        CacheUtil.remove(token);
    }

    @Override
    public void updatePassword(String id, String oldPassword, String newPassword) throws ServiceException{
        AdminUser adminUser = adminUserDao.findById(id);
        if(!adminUser.getPassword().equals(oldPassword)){
            throw new ServiceException(ErrorConstant.ec_param_error,ErrorConstant.em_password_error);
        }
        adminUser.setPassword(newPassword);
        adminUserDao.update(adminUser);
    }
}
